﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using Toodledo.Model;
using System.Collections.Specialized;
using System.Threading;
using Toodledo.Security;
using Toodledo.Services.Helpers;
using Toodledo.Services.Interfaces;
using Toodledo.Model;


namespace Toodledo.Services
{
    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    internal sealed class SearchParamNameAttribute   : Attribute
    {
        // See the attribute guidelines at 
        //  http://go.microsoft.com/fwlink/?LinkId=85236
        private readonly string _paramName;

        // This is a positional argument
        public SearchParamNameAttribute(string name)
        {
            _paramName = name;
        }

        public string ParamName
        {
            get { return _paramName; }
        }

        public override string ToString()
        {
            return _paramName;
        }
    }
    public class TaskSearchParams
    {
        public string Title { get; set; }
        public string Tag { get; set; }
        [SearchParamName("folder")]
        public string FolderId { get; set; }
        [SearchParamName("context")]
        public string ContextId { get; set; }
        [SearchParamName("goal")]
        public string GoalId { get; set; }
        public int? Priority{ get; set; }
        public int? Repeat { get; set; }
        public int? Status { get; set; }
        [SearchParamName("parent")]
        public string ParentTaskId { get; set; }
        [SearchParamName("")]
        public int? DueInMinutes { get; set; }
        public int? DueAfterMinutes { get; set; }
        public DateTime? DueBeforeDate { get; set; }
        public DateTime? DueAfterDate { get; set; }
        public DateTime? StartBeforeDate { get; set; }
        public DateTime? StartAfterDate { get; set; }
        public DateTime? ModifiedBeforeDate { get; set; }
        public DateTime? ModifiedAfterDate { get; set; }
        public DateTime? CompletedBeforeDate { get; set; }
        public DateTime? CompletedAfterDate { get; set; }
        public bool? ExcludeCompleted { get; set; }
        public bool? IsStarred { get; set; }
        public string Id { get; set; }
        public int? FromRecord { get; set; }
        public int? ToRecord { get; set; }
        public bool? ShowDatesAsUnixTimestame { get; set; }
    }
    public class TaskService : ToodledoServiceBase
    {
        public TaskService(IToodledoConnector connector) : base (connector)
        {            
        }

        public List<Task> GetTasks(TaskSearchParams searchParams)
        {
            if (Thread.CurrentPrincipal.Identity.IsAuthenticated)
            {
                var currentIdentity = Thread.CurrentPrincipal.Identity as ToodledoIdentity;

                if (currentIdentity != null)
                {
                    var queryParams = new NameValueCollection { { "method", "getTasks" }, { "key", currentIdentity.AuthKey } };
                    if (searchParams!= null)
                    {
                        AddSearchParamsToQuery(queryParams, searchParams);
                    }
                    var response = _toodledoConnector.GetToodledoResponse(queryParams);
                    return ToodledoExtensions.AsTaskList(response);
                }
            }
            throw new UnauthorizedAccessException("You are not authorized");
        }

        private static void AddSearchParamsToQuery(NameValueCollection queryParams, TaskSearchParams searchParams)
        {
            foreach (PropertyInfo prop in typeof(TaskSearchParams).GetProperties())
            {
                string paramName = GetQueryParamName(prop);
                string paramValue = GetStringValue(searchParams, prop);
                if (!string.IsNullOrEmpty(paramValue))
                {
                    queryParams.Add(paramName.ToLower(), paramValue);
                }
            }
        }

        private static string GetStringValue(TaskSearchParams searchParams, PropertyInfo prop)
        {
            if (searchParams != null && prop != null)
            {
                var paramValue = prop.GetValue(searchParams, null);
                if (paramValue != null)
                {
                    string stringValue;
                    if (prop.DeclaringType == typeof (string))
                    {
                        stringValue = ((string) paramValue).Replace("&", "%26").Replace(";", "%3B");
                    }
                    else if (prop.DeclaringType == typeof (DateTime?))
                    {
                        stringValue = ((DateTime?) paramValue).Value.ToString("YYYY-MM-DD");
                    }
                    else if (prop.DeclaringType == typeof (bool?))
                    {
                        var boolValue = ((bool?) paramValue).Value ? 1 : 0;
                        stringValue = boolValue.ToString();
                    }
                    else
                        stringValue = paramValue.ToString();
                    return stringValue;
                }
                return string.Empty;
            }
            throw new InvalidOperationException("Either search parameter is null or specified property is null");
        }

        private static string GetQueryParamName(PropertyInfo prop)
        {
            var attribs = prop.GetCustomAttributes(typeof (SearchParamNameAttribute), true);
            var paramName = attribs.Count() == 1 ? attribs[0].ToString() : prop.Name;
            return paramName;
        }
    }
}
